package com.paddyi.controller;

import com.paddyi.commons.http.HttpResult;
import com.paddyi.model.Resource;
import com.paddyi.model.Role;
import com.paddyi.model.vo.UserVo;
import com.paddyi.service.IResourceService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 资源 (Resource)
 *
 * @author paddy
 * @since 2019-04-26 04:34:10
 */
@RestController
@RequestMapping("resource")
public class ResourceController extends BaseController {

    @Reference(version = "${demo.service.version}")
    private IResourceService resourceService;

    /**
     * 保存资源
     *
     * @param record
     * @return
     */
    @PostMapping(value = "/add")
    public HttpResult add(@RequestBody Resource record) {
        Long userId = getUserId();
        Date date = new Date();
        record.setCreateUserId(userId);
        record.setCreateTime(date);
        record.setUpdateUserId(userId);
        record.setUpdateTime(date);
        return HttpResult.ok(resourceService.save(record));
    }

    /**
     * 删除资源
     *
     * @param records
     * @return
     */
    @PostMapping(value = "/delete")
    public HttpResult delete(@RequestBody List<Resource> records) {
        List list = new ArrayList();
        for(Resource re:records){
            list.add(re.getId());
        }
        return HttpResult.ok(resourceService.removeByIds(list));
    }

    /**
     * 修改资源
     *
     * @param record
     * @return
     */
    @PostMapping(value = "/edit")
    public HttpResult edit(@RequestBody Resource record) {
        record.setUpdateTime(new Date());
        record.setUpdateUserId(getUserId());
        return HttpResult.ok(resourceService.updateById(record));
    }

    /**
     * 基础分页查询,条件查询只支持等于，如果想要更高级的功能，比如大于小于等等，请自己写吧
     *
     * @return
     */
    @PostMapping (value = "/findPage")
    public HttpResult findPage() {

        return HttpResult.ok(resourceService.findTree());
    }

    /**
     * 根据主键查询
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/find")
    public HttpResult find(@RequestParam Long id) {
        return HttpResult.ok(resourceService.getById(id));
    }

    /**
     * 查询有权限的菜单
     *
     * @return
     */
    @GetMapping(value = "/findNavTree")
    public HttpResult findNavTree() {
        UserVo user = (UserVo) SecurityUtils.getSubject().getPrincipal();
        long a =  SecurityUtils.getSubject().getSession().getTimeout();
        System.out.println(a);
        List<Long> roleIds = new ArrayList<>();
        for(Role role : user.getRoleList()){
            roleIds.add(role.getId());
        }

        return HttpResult.ok(resourceService.selectResourceTreeByLoginName(roleIds));
    }
}
